<template>
    <div class="page-builder-menu" :class="{'active': pinMenu, 'active-float': isActive }" ref="jmenus">
        <div class="page-builder-item-tools">
            <div class="page-builder-item-cell">
                <div class="page-builder-item-tab fa fa-map-pin" :class="{ 'active pin': pinMenu }" @click="pinMenu = !pinMenu"
                      v-tippy="{ arrow: true, placement: 'left' }" content="钉住"></div>
                <div class="page-builder-item-tab" :class="{ 'active': menuTab === 'base' }" @click="handleMenuSelect('base')"
                     v-tippy="{ arrow: true }" content="基础组件">基础组件</div><!-- @mouseenter="handleMenuEnter('base')" @mouseleave="handleMenuLeave" -->
                <div class="page-builder-item-tab" :class="{ 'active': menuTab === 'cloud' }" @click="handleMenuSelect('cloud')"
                     v-tippy="{ arrow: true, placement: 'right' }" content="云端组件">云端组件</div><!-- @mouseenter="handleMenuEnter('cloud')" @mouseleave="handleMenuLeave" -->
                <div class="page-builder-item-tab" @click="handlePageItemSelectShow()"
                     v-tippy="{ arrow: true, placement: 'right' }" content="从已设计的页面中选择模块">页面中选择</div>
            </div>
            <!--<div class="page-builder-item-tab" :class="{ 'active': menuTab === 'compNodeTree' }"
                 @mouseenter="handleMenuEnter('compNodeTree')" @mouseleave="handleMenuLeave"
                 v-tippy="{ arrow: true, placement: 'right' }" content="组件节点树">组件节点树</div>-->
        </div>
        <div v-if="isActive || pinMenu" class="page-builder-panel-collapse fa fa-chevron-left" @click="handleMenuHide"></div>
        <perfect-scrollbar v-show="menuTab === 'base'" class="ele-design-eles" :class="{ 'active': pinMenu }">
            <div class="page-builder-menu-group">通用</div>
            <draggable v-model="elemsCommon"
                       :options="{
                           group: { name: 'items', pull: 'clone', put: false },
                           sort: false,
                           ghostClass: 'sortable-ghost',
                           chosenClass: 'sortable-chosen',
                           dragClass: 'sortable-drag'
                       }"
                       element="ul" :clone="handleDragClone"
                       @start="drag=true" @end="drag=false">
                <template v-for="ele in elemsCommon">
                    <li :key="ele.component"
                        @drag="handleDrag($event, ele)" @dragend="handleDragend($event, ele)"
                        @click="handleMenuClick(ele)" draggable="true" unselectable="on"
                        v-tippy="{ arrow: true, placement: 'right' }" :content="ele.name">
                        <i class="fa" :class="ele.icon"></i>
                        <p v-text="ele.name"></p>
                    </li>
                </template>
            </draggable>
            <div class="page-builder-menu-group">布局</div>
            <draggable v-model="elemsLayout"
                       :options="{
                           group: { name: 'items', pull: 'clone', put: false },
                           sort: false,
                           ghostClass: 'sortable-ghost',
                           chosenClass: 'sortable-chosen',
                           dragClass: 'sortable-drag'
                       }"
                       element="ul" :clone="handleDragClone"
                       @start="drag=true" @end="drag=false">
                <template v-for="ele in elemsLayout">
                    <li :key="ele.component"
                        @drag="handleDrag($event, ele)" @dragend="handleDragend($event, ele)"
                        @click="handleMenuClick(ele)" draggable="true" unselectable="on"
                        v-tippy="{ arrow: true, placement: 'right' }" :content="ele.name">
                        <i class="fa" :class="ele.icon"></i>
                        <p v-text="ele.name"></p>
                    </li>
                </template>
            </draggable>
            <div class="page-builder-menu-group">表单元素</div>
            <draggable v-model="elemsForm"
                       :options="{
                           group: { name: 'items', pull: 'clone', put: false },
                           sort: false,
                           ghostClass: 'sortable-ghost',
                           chosenClass: 'sortable-chosen',
                           dragClass: 'sortable-drag'
                       }"
                       element="ul" :clone="handleDragClone"
                       @start="drag=true" @end="drag=false">
                <template v-for="ele in elemsForm">
                    <li :key="ele.component"
                        @drag="handleDrag($event, ele)" @dragend="handleDragend($event, ele)"
                        @click="handleMenuClick(ele)" draggable="true" unselectable="on"
                        v-tippy="{ arrow: true, placement: 'right' }" :content="ele.name">
                        <i class="fa" :class="ele.icon"></i>
                        <p v-text="ele.name"></p>
                    </li>
                </template>
            </draggable>
            <div class="page-builder-menu-group">表单组件</div>
            <draggable v-model="elemsJForm"
                       :options="{
                           group: { name: 'items', pull: 'clone', put: false },
                           sort: false,
                           ghostClass: 'sortable-ghost',
                           chosenClass: 'sortable-chosen',
                           dragClass: 'sortable-drag'
                       }"
                       element="ul" :clone="handleDragClone"
                       @start="drag=true" @end="drag=false">
                <template v-for="ele in elemsJForm">
                    <li :key="ele.component"
                        @drag="handleDrag($event, ele)" @dragend="handleDragend($event, ele)"
                        @click="handleMenuClick(ele)" draggable="true" unselectable="on"
                        v-tippy="{ arrow: true, placement: 'right' }" :content="ele.name">
                        <i class="fa" :class="ele.icon"></i>
                        <p v-text="ele.name"></p>
                    </li>
                </template>
            </draggable>
            <div class="page-builder-menu-group">报表</div>
            <draggable v-model="elemsChart"
                       :options="{
                           group: { name: 'items', pull: 'clone', put: false },
                           sort: false,
                           ghostClass: 'sortable-ghost',
                           chosenClass: 'sortable-chosen',
                           dragClass: 'sortable-drag'
                       }"
                       element="ul" :clone="handleDragClone"
                       @start="drag=true" @end="drag=false">
                <template v-for="ele in elemsChart">
                    <li :key="ele.component"
                        @drag="handleDrag($event, ele)" @dragend="handleDragend($event, ele)"
                        @click="handleMenuClick(ele)" draggable="true" unselectable="on"
                        v-tippy="{ arrow: true, placement: 'right' }" :content="ele.name">
                        <i class="fa" :class="ele.icon"></i>
                        <p v-text="ele.name"></p>
                    </li>
                </template>
            </draggable>
        </perfect-scrollbar>
        <div v-show="menuTab === 'cloud'" class="ele-design-eles ele-design-eles-cloud" :class="{ 'active': pinMenu }">
        <!--<perfect-scrollbar v-else class="ele-design-eles" :class="{ 'active': pinMenu }">-->
            <el-popover placement="bottom" v-model="appCateVisible" popper-class="app-cate-popover">
                <app-cate style="margin-right: 0px;" @select="handleAppCateChange"></app-cate>
                <el-button slot="reference" class="app-cate-trigger" plain size="medium">
                    <i :class="appCate && appCate.icon"></i> {{ appCate ? appCate.group_name: '全部' }}
                    <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
            </el-popover>
            <perfect-scrollbar style="height: 100%;">
                <draggable v-model="elemsCloud" class="page-cloud-comps"
                           :options="{
                               group: { name: 'items', pull: 'clone', put: false },
                               sort: false,
                               ghostClass: 'sortable-ghost',
                               chosenClass: 'sortable-chosen',
                               dragClass: 'sortable-drag'
                           }"
                           element="div" :clone="handleDragClone"
                           @start="drag=true" @end="drag=false">
                    <!--<li :key="ele.component"
                        v-tippy="{ arrow: true, placement: 'right' }" :content="ele.name">
                        <i class="fa" :class="ele.icon"></i>
                        <p v-text="ele.name"></p>
                    </li>-->

                    <template v-for="comp in elemsCloud">
                        <!--<div class="comp pbm-comp-cloud" :class="{ 'has-bg': !!comp.thumb }" :key="comp.component"
                             :style="{ backgroundImage: `url(${ comp.thumb || ''})` }"
                             @drag="handleDrag($event, comp)" @dragend="handleDragend($event, comp)"
                             @click="handleMenuClick(comp)" draggable="true" unselectable="on"
                             v-tippy="{ arrow: true, placement: 'right' }" :content="comp.remark || comp.name">
                            <div class="comp-body">
                                <span class="art-font comp-title">{{comp.comp_name}}</span>
                            </div>
                            <div class="comp-foot">
                                <span class="art-font" v-text="comp.name"></span>
                            </div>
                        </div>-->

                        <div class="page-card" :key="comp.component"
                             @drag="handleDrag($event, comp)" @dragend="handleDragend($event, comp)"
                             @click="handleMenuClick(comp)" draggable="true" unselectable="on"
                             v-tippy="{ arrow: true }" :content="comp.remark || comp.comp_name">
                            <page-thumb :img="$utils.get(comp, 'thumb')" :width="192" :height="120">
                                <div class="page-code" v-text="comp.comp_name" v-copy="comp.comp_name"
                                     v-tippy="{ arrow: true, placement : 'left' }" content="点击复制"></div>
                                <!--<i class="page-card-action fa fa-eye preview" v-tippy="{ arrow: true, placement : 'left' }" content="预览"
                                   @click="handleView(comp)"></i>-->
                            </page-thumb>
                            <div class="page-info">
                                <!--<i class="page-type fa" :class="{
                                'fa-mobile-alt page-type-design': isCompTypeH5(comp),
                                'fa-laptop page-type-custom': isCompTypePc(comp) }"></i>-->
                                <div class="art-font page-title" v-text="comp.name"></div>
                            </div>
                        </div>
                    </template>
                </draggable>
            </perfect-scrollbar>

            <div>
                <el-pagination small
                        @current-change="loadCloudComps"
                        :current-page.sync="pagination.page"
                        :page-size.sync="pagination.pageSize"
                        layout="prev, next, total"
                        :total="pagination.total">
                </el-pagination>
            </div>
        <!--</perfect-scrollbar>-->
        </div>

        <!--<div v-show="menuTab === 'compNodeTree'" class="ele-design-eles" :class="{ 'active': pinMenu }">
            <builder-nodes v-on="$listeners" v-bind="$attrs"></builder-nodes>
        </div>-->

        <!--<el-dialog title="选择已有页面元素" :visible.sync="pageItemSelectWinShow" custom-class="m-dialog-fullscreen"
                   :close-on-click-modal="false" :append-to-body="true">
            <div style="width: 100%;height: 100%;overflow-y: auto;">
                <page-item-select :query-page-type="pageType"></page-item-select>
            </div>
        </el-dialog>-->

        <el-dialog title="选择已有页面组件" custom-class="m-dialog-fullscreen"
                :close-on-click-modal="false" :append-to-body="true"
                :visible.sync="pageItemSelectWinShow">
            <page-item-picker :query-page-type="pageType" @copyItem="handleCopyItem" @referItem="handleReferItem"
                              @close="pageItemSelectWinShow = false"></page-item-picker>
        </el-dialog>
    </div>
</template>

<script>
    import mutil            from '../utils/mutil';
    import ELE_TYPES_Fn     from './ele/ele-types';
    import BuilderNodes     from './builder-nodes';
    import PageItemPicker   from './pages/page-item-picker';
    import referDef         from './ele/refer/def';

    export default {
        name: "builder-menu",
        props: {
            pageType: {
                type: [ String, Number ],
                default: 1
            },
            items: Array,
            inPinMenu: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                pinMenu: false,
                isActive: false,
                menuTab: 'base',
                elems: [],
                elemsLayout: [],
                elemsChart: [],
                elemsForm: [],
                elemsJForm: [],
                elemsCommon: [],

                appCateVisible: false,
                appCate: null,
                elemsCloud: [],
                // queryAppId: -200,
                loading: false,
                pagination: {
                    page: 1,
                    pageSize: 50,
                    total: 0
                },
                timer: null,
                pageItemSelectWinShow: false
            }
        },
        components: {
            BuilderNodes,
            PageItemPicker
        },
        watch: {
            'pageType'() {
                this.initElems();
            },
            'pinMenu'(val) {
                this.$emit("pinMenuChange", val)
            }
        },
        mounted() {
            this.initElems();
            this.loadCloudComps();
            this.pinMenu = this.inPinMenu;
        },
        methods: {
            ...mutil,
            initElems() {
                let eles = [];
                let layouts = [ 'jzlLayout', 'jzlPageSub', 'jzlPageTabs' ];
                /*'jzlPageInput', 'jzlPageSwitch', 'jzlPageSelect', 'jzlPageCascader'*/
                let forms = [ 'c$inputComp', 'c$numberComp', 'c$radioComp', 'c$checkboxComp', 'c$switchComp', 'c$mbComp', 'c$colorComp',
                              'c$phoneComp', 'c$editorComp', 'c$idcardComp', 'c$fileComp',
                              'c$imageComp', 'c$linkComp', 'c$matrixComp', 'c$iconComp',
                              'c$roleComp', 'c$signComp', 'c$sliderComp',
                              'c$starComp', 'c$tagComp', 'c$timeComp', 'c$videoComp' ];
                let jForms = [ 'jzlDataList', 'jzlDataForm' ];
                let elemsChart = [];
                let elemsLayout = [];
                let elemsCommon = [];
                let elemsForm = [];
                let elemsJForm = [];

                let ELE_TYPES = ELE_TYPES_Fn(this.pageType);

                for(let i in ELE_TYPES) {
                    let it = ELE_TYPES[i];

                    if(this.$putils.isChartComponent(it.component)) {
                        elemsChart.push(it);
                    } else if(_.indexOf(layouts, it.component) >= 0) {
                        elemsLayout.push(it);
                    } else if(_.indexOf(forms, it.component) >= 0) {
                        elemsForm.push(it);
                    } else if(_.indexOf(jForms, it.component) >= 0) {
                        elemsJForm.push(it)
                    } else {
                        elemsCommon.push(it);
                    }

                    eles.push(it);
                }

                this.elems = eles;
                this.elemsLayout = elemsLayout;
                this.elemsChart = elemsChart;
                this.elemsForm = elemsForm;
                this.elemsJForm = elemsJForm;
                this.elemsCommon = elemsCommon;
            },
            handleDragClone(def) {
                let comp_lib = _.get(def, "comp_lib");
                let comp_def = _.get(def, "comp_def");
                let ndef = def;

                // is_dynccomp
                if(comp_lib && comp_def) {
                    ndef = _.cloneDeep(comp_def || {});
                    ndef = _.defaultsDeep({
                        component: _.get(def, 'comp_name'),
                        is_dynccomp: 1,
                        comp_lib: _.get(def, 'comp_lib'),
                        icon: _.get(def, 'icon'),
                        name: _.get(def, 'name'),
                        project_id: this.projectId,
                    }, ndef);
                }

                // console.log(`----------------->>>>> handleDragClone x: ${ ndef }`);
                // console.log(`----------------->>>>> handleDragClone y: ${ ELE_TYPES_Fn(this.pageType) }`);
                return this._dragClone(ndef, this.items);
            },
            handleDrag(event, ele) {
                this.$emit("menuDrag", { event, ele })
            },
            handleDragend(event, ele) {
                this.$emit("menuDragend", { event, ele })
            },
            async loadCloudComps() {
                let app_id = -1;
                let cate = -1;
                let query = {};
                let queryAppId = _.get(this.appCate, "group_id");

                this.loading = true;

                if(queryAppId === -200) {
                    cate = -1;
                } else if(queryAppId === -100) {
                    // project_id = -1;
                    cate = 1;
                } else if(queryAppId === -1) {
                    // project_id = this.app.project_id;
                    cate = 2;
                } else {
                    cate = 3;
                    app_id = queryAppId;
                }

                // query.project_id = project_id;
                query.app_id = app_id;
                query.cate = cate;

                let ret = await this.$japi.comp.getCompList(query, this.pagination);
                this.elemsCloud = _.get(ret, 'rows', []);
                this.pagination.total = _.get(ret, 'count', 0);

                this.loading = false;
            },
            handleAppCateChange(appCate) {
                this.appCate = appCate;
                this.appCateVisible = false;
                this.loadCloudComps()
            },
            handleMenuSelect(tab) {
                this.menuTab = tab;
                this.isActive = true;
            },
            handleMenuHide() {
                this.isActive = false;
                this.pinMenu = false;
            },
            handleMenuEnter(tab) {
                if(this.timer) clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    this.menuTab = tab
                }, 150);
            },
            handleMenuLeave() {
                if(this.timer) {
                    clearTimeout(this.timer);
                    this.timer = null;
                }
            },
            handleMenuClick(menu) {
                this.$emit("menu-click", menu);
            },
            handlePageItemSelectShow() {
                this.pageItemSelectWinShow = true;
            },
            handleCopyItem(item) {
                let code = this.$utils.getNanoid(10);
                let copyItem = _.defaultsDeep({
                    page_item_code: code,
                    alias: this._getAlias(code),
                    project_id: this.projectId,
                    module_name: code,
                    i: code
                }, item);   // _.merge({}, this.items[index]);

                delete copyItem.page_item_id;

                let boxStyle = _.get(copyItem, "box_style");
                let eleStyle = _.get(copyItem, "ele_style");
                this.resetCode(boxStyle);
                this.resetCode(eleStyle);

                this.handleMenuClick(copyItem);
                this.pageItemSelectWinShow = false;
            },
            handleReferItem(item) {
                let code = this.$utils.getNanoid(10);
                let referItem = _.defaultsDeep({
                    page_item_code: code,
                    alias: this._getAlias(code),
                    module_name: code,
                    i: code,
                    project_id: this.projectId,
                    refer: item,
                    refer_item_id: _.get(item, 'page_item_id')
                }, _.cloneDeep(referDef));

                this.handleMenuClick(referItem);
                this.pageItemSelectWinShow = false;
            }
        }
    }
</script>
